<%--
  Created by IntelliJ IDEA.
  User: ridbor001
  Date: 2025/5/5
  Time: 22:11
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<button class="theme-toggle" onclick="toggleTheme()">🌙</button>
<div class="course-form">
    <div class="form-header">
        <a href="rDBDashboard.jsp" class="btn-back">
            <i class="fas fa-arrow-left"></i>
            返回仪表盘
        </a>
    <h4>新建教学科目</h4>
    </div>
    <form action="courseManage" method="post">
        <!-- 课程基础信息 -->
        <div class="form-group">
            <label>课程名称：</label>
            <input type="text" name="courseName" required
                   placeholder="例：Java高级编程" maxlength="50">
        </div>

        <div class="form-group">
            <label>开课学期：</label>
            <select name="term" class="form-control">
                <option value="2023春季">2025春季</option>
                <option value="2023秋季">2025秋季</option>
                <option value="2024春季">2025春季</option>
                <option value="2024秋季">2025秋季</option>
                <option value="2025春季">2025春季</option>
                <option value="2025秋季">2025秋季</option>
                <option value="2026春季">2025春季</option>
                <option value="2026秋季">2025秋季</option>
            </select>
        </div>

        <!-- 学生选择下拉框 -->
        <div class="form-group custom-student-select">
            <label>选择学生：</label>

            <!-- 搜索框 -->
            <div class="search-box">
                <input type="text" id="studentSearch"
                       placeholder="输入姓名/学号/班级进行搜索"
                       class="search-input">
                <button type="button" class="search-btn" onclick="searchStudents()" >
                    搜索
                    <i class="fas fa-search"></i>
                </button>
            </div>

            <!-- 搜索结果区域 -->
            <div class="search-results">
                <div class="results-header">
                    <label class="select-all">
                        <input type="checkbox" id="selectAll"
                               onchange="toggleSelectAll(this)">
                        全选当前结果
                    </label>
                    <span class="results-count" id="resultsCount"></span>
                </div>

                <div class="results-list" id="resultsList"></div>
            </div>
            <div class="form-group">
                <label>授课教师：</label>
                <select name="teacherId" id="teacherSelect" class="form-control">
                    <option value="">-- 请选择教师 --</option>
                    <c:forEach items="${teachers}" var="teacher">
                        <option value="${teacher.teacherId}">
                                ${teacher.name}（${teacher.teacherId}）
                        </option>
                    </c:forEach>
                </select>
            </div>


            <!-- 隐藏的表单字段 -->
            <input type="hidden" name="studentIds" id="studentIds">
        </div>
        <button type="submit" class="btn-submit">创建课程</button>
    </form>
</div>

<!-- 引入Select2增强下拉框 -->
<!-- CSS -->

<!-- CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<!-- JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

<script>
    // 初始化已选学生集合
    const selectedStudents = new Set();
    const allStudents = [
        <c:forEach items="${students}" var="student" varStatus="status">
        {
            id: "${student.studentId}",
            name: "${student.name}",
            className: "${student.className}",
            studentId: "${student.studentId}"
        }<c:if test="${not status.last}">, </c:if>
        </c:forEach>
    ];
    $(document).ready(function () {
        $('.select2-multi').select2({
            width: '100%',
            placeholder: "输入姓名/学号/班级进行搜索",
            allowClear: true,
            minimumResultsForSearch: 0, // 强制显示搜索框

            matcher: function (params, data) { // 自定义搜索匹配规则
                // 原始匹配逻辑
                var originalMatcher = $.fn.select2.defaults.defaults.matcher;
                var result = originalMatcher(params, data);

                if (result && params.term && params.term.length > 0) {
                    return result;
                }

                // 自定义多字段匹配
                var searchTerm = params.term.toLowerCase();
                var studentInfo = data.text.toLowerCase(); // 选项文本格式：姓名 (班级-学号)

                // 拆分信息
                var parts = studentInfo.match(/(.*)\s+(.*)班[^0-9]*(.*)/);
                if (parts) {
                    var name = parts[1];
                    var className = parts[2];
                    var studentId = parts[3];

                    // 多条件匹配
                    return (name.indexOf(searchTerm) > -1) ||
                    (studentId.indexOf(searchTerm) > -1) ||
                    (className.indexOf(searchTerm) > -1) ?
                        data : null;
                }
                return data;
            }
        });
    });

    function searchStudents() {
        const searchTerm = document.getElementById('studentSearch').value.toLowerCase();

        const filtered = allStudents.filter(s =>
            s.name.toLowerCase().includes(searchTerm) ||
            s.studentId.includes(searchTerm) ||
            s.className.toLowerCase().includes(searchTerm)
        );

        displayResults(filtered);
    }

    // 显示搜索结果
    function displayResults(students) {
        const list = document.getElementById('resultsList');
        const count = document.getElementById('resultsCount');

        list.innerHTML = '';
        <%--count.textContent = `找到 ${students.length} 个结果`;--%>

        students.forEach(student => {
            const item = document.createElement('div');
            item.className = 'student-item';

            // 使用字符串拼接确保正确解析
            item.innerHTML =
                '<label>' +
                '   <input type="checkbox" value="' + student.id + '"' +
                (selectedStudents.has(student.id) ? ' checked' : '') +
                '       onchange="toggleStudent(\'' + student.id + '\', this.checked)">' +
                '   ' + student.name + ' (' + student.className + '班 - ' + student.studentId + ')' +
                '</label>';

            list.appendChild(item);
        });

        document.getElementById('selectAll').checked =
            students.length > 0 && students.every(s => selectedStudents.has(s.id));
    }

    // 切换单个学生选择
    function toggleStudent(id, checked) {
        if (checked) {
            selectedStudents.add(id);
        } else {
            selectedStudents.delete(id);
        }
        updateSelection();
    }

    // 全选/取消全选
    function toggleSelectAll(checkbox) {
        const currentResults = [...document.querySelectorAll('#resultsList .student-item input')];

        currentResults.forEach(input => {
            input.checked = checkbox.checked;
            toggleStudent(input.value, checkbox.checked);
        });
    }

    // 更新已选列表和隐藏字段
    function updateSelection() {
        // 更新隐藏字段
        document.getElementById('studentIds').value = Array.from(selectedStudents).join(',');

        <%--// 更新已选列表显示--%>
        <%--const selectedList = document.getElementById('selectedList');--%>
        <%--const count = document.getElementById('selectedCount');--%>

        <%--selectedList.innerHTML = '';--%>
        <%--count.textContent = selectedStudents.size;--%>

        <%--selectedStudents.forEach(id => {--%>
        <%--    const student = allStudents.find(s => s.id === id);--%>
        <%--    const item = document.createElement('div');--%>
        <%--    item.className = 'selected-item';--%>
        <%--    item.innerHTML = `--%>
        <%--    ${student.name} (${student.studentId})--%>
        <%--    <button type="button" onclick="toggleStudent('${id}', false); searchStudents()">--%>
        <%--        ×--%>
        <%--    </button>--%>
        <%--`;--%>
        <%--    selectedList.appendChild(item);--%>
        // });
    }

    // 初始化搜索
    document.getElementById('studentSearch').addEventListener('keypress', e => {
        if (e.key === 'Enter') {
            searchStudents();
            e.preventDefault();
        }
    });

        // 初始化主题
        function initTheme() {
        const savedTheme = localStorage.getItem('theme') || 'dark';
        const isLight = savedTheme === 'light';
        document.body.classList.toggle('light-mode', isLight);
        document.querySelector('.theme-toggle').textContent = isLight ? '☀️' : '🌙';
    }

        // 切换主题
        function toggleTheme() {
        const body = document.body;
        const isLight = !body.classList.contains('light-mode');
        body.classList.toggle('light-mode');
        localStorage.setItem('theme', isLight ? 'light' : 'dark');
        document.querySelector('.theme-toggle').textContent = isLight ? '☀️' : '🌙';
    }

        // 页面加载时初始化
        window.addEventListener('load', initTheme);
    $(document).ready(function () {
        // 教师下拉框启用 Select2
        $('#teacherSelect').select2({
            width: '100%',
            placeholder: "输入姓名或工号搜索教师",
            allowClear: true,
            minimumResultsForSearch: 0 // 始终显示搜索框
        });

        // 学生多选下拉框的 Select2 逻辑（已存在）...
    });


</script>
<link href="./css/rDBCourseAdd.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">